const {Server} = require('socket.io')
const http = require('http')
const express = require('express')
const process = require('node:process')
const app = express()

const server = http.createServer(app)
const io = new Server(server, {
  cors: {
    origin: process.env.URL_FRONT,
    methods: ['GET', 'POST'],
  },
})

io.on('connection', (socket) => {
  console.log(`User connected: ${socket.id}`)

  socket.on('disconnect', () => {
    console.log(`User disconnected: ${socket.id}`)
  })

  socket.on('chat message', (msg) => {
    console.log(`Message received: ${msg}`)
    io.emit('newMessage', msg)
  })
})

module.exports = {app, server, io}
